package com.pompom.matchcrawler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import nl.ansuz.android.steam.dota.request.DotaRequest;
import nl.ansuz.android.steam.request.ISteamRequest;
import nl.ansuz.android.steam.request.SteamRequest;
import nl.ansuz.android.steam.util.GsonUtil;

import com.google.gson.Gson;
import com.google.gson.stream.MalformedJsonException;

public abstract class AbstractFecher<E> {
	private static final GsonUtil gsonUtil = new GsonUtil();
	private static final Gson gson = new Gson();
	private int responseError=ResponseTypeChecker.NO_ERROR;
	private boolean printResponse=false;
	public E fetch() {
		ISteamRequest getMatchDetails = getSteamRequest();
		Map<String, String> params = new HashMap<String, String>();

		params.put(SteamRequest.Parameter.API_KEY, "18755ABB58C0BE96815AE471FBB1C3F2");

		setParams(params);

		String url = getMatchDetails.createRequestUrl(DotaRequest.ApplicationID.LIVE, params);

		String response = null;
		while (response==null)
		{
			try {
				response = ManipulaHttp2.executaConsulta(url);
			} catch (IOException e) { 
				System.out.println("Error fetching http. sleep a while.");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) { 
					e1.printStackTrace();
				}
			}
		}

		if(response != null) {
			responseError= ResponseTypeChecker.checkResponse(response);

			if (printResponse)
				System.out.println(response);

			E retVal =  null;
			try{
				retVal=gson.fromJson(gsonUtil.getStrippedDotaResult(response), getResponseType()); 
			} 
			catch (Exception e)
			{ 
				System.out.println("malformed json result. skipping");
				retVal=null;
			}
			return retVal;
		}

		return null;
	}

	public int getResponseError()
	{
		return responseError;
	}
	protected abstract Class<E> getResponseType();
	protected abstract ISteamRequest getSteamRequest();
	protected abstract void setParams(Map<String, String> params);

	public boolean isPrintResponse() {
		return printResponse;
	}

	public void setPrintResponse(boolean printResponse) {
		this.printResponse = printResponse;
	}
}
